<template>
  <div class="app-login">
    <div class="login">
      <h1>系统登录</h1>
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password" type="password" show-password />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="checked">记住密码</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { useRouter } from "vue-router";
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { authLogin } from '@/server/user'
import { getCenter } from '@/server/center'
import { useStore } from "vuex"
const store = useStore()
const router = useRouter()
interface RuleForm {
  name: string
  password: string
}
const checked = ref(false)
const formSize = ref('large')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  name: '',
  password: ''
  // name: 'admin',
  // password:'1q2w3E*'
})

const rules = reactive<FormRules<RuleForm>>({
  name: [
    { required: true, message: 'Please input Activity name', trigger: 'blur' }
  ],
  password: [
    { required: true, message: 'Please input Activity password', trigger: 'blur' },
    { min: 6, max: 20, message: 'Length should be 6 to 20', trigger: 'blur' },
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const { password, name } = ruleForm
      const params = {
        grant_type: "password",
        client_secret: "",
        client_id: "Wangi_App",
        password,
        username: name,
        scope: "Wangi offline_access"
      }
      try {
        //登录
        const result = await authLogin(params)
        ElMessage.success("登录成功")
        localStorage.setItem("token", result.access_token)
        //记住密码
        if (checked.value) {
          localStorage.setItem("checkedUser", JSON.stringify(ruleForm))
        } else {
          localStorage.removeItem("checkedUser")
        }
        //储存个人信息
        const data = await getCenter()
        localStorage.setItem("user_info", JSON.stringify(data))
        store.commit('changeUserinfo', data)
        setTimeout(() => {
          router.push({ path: '/index' })
        }, 1000);
      } catch (err) {
        console.log("🚀 ~ awaitformEl.validate ~ err:", err)
        ElMessage.error("登录失败")
      }
      // axios.post("/webapi/api/account/login",{
      //   password,
      //   userNameOrEmailAddress:name
      // }).then(res=>{
      //   console.log(res)
      // })

    } else {
      console.log('error submit!', fields)
    }
  })
}

const checkedUser = localStorage.getItem('checkedUser')
if (checkedUser) {
  const data = JSON.parse(checkedUser)
  ruleForm.name = data.name
  ruleForm.password = data.password
  checked.value = true
}

</script>
<style lang="scss" scoped>
.app-login {
  background-color: #2d3a4b;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100%;
  color: #fff;

  .login {
    box-shadow: 0 0 100px #fff;
    border-radius: 10px;
    width: 30rem;
    padding: 2rem;

    .el-checkbox {
      color: #fff;
    }

    .el-button {
      width: 100%;
    }

    ::v-deep .el-form-item__label {
      color: #fff;
    }
  }

  text-align: center;

  h1 {
    margin-bottom: 2rem;
  }
}
</style>